import os

from flask import send_from_directory
from werkzeug.utils import secure_filename


class FileMgrServ:
    def __init__(self, logger):
        self.logger = logger
        # 使用基于项目根目录的绝对路径
        self.upload_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..', 'uploads'))
        os.makedirs(self.upload_dir, exist_ok=True)

    def upload(self, file):
        """
        上传文件处理
        参数:
            file: Flask文件对象
        返回:
            (success, message) 元组
        """
        try:
            # 保存文件
            self.logger.debug(f"file path: {self.upload_dir}")
            filepath = os.path.join(self.upload_dir, file.filename)
            file.save(filepath)
            return True, filepath
        except Exception as e:
            self.logger.exception(f"上传文件异常: {str(e)}")
            return False, str(e)

    def get_images(self, filename):
        self.logger.debug(f"file path: {self.upload_dir}")
        return send_from_directory(self.upload_dir, filename)

    def get_file(self, filename):
        """
        获取文件
        参数:
            filename: 文件名
        返回:
            (success, filepath_or_error) 元组
        """
        try:
            # 安全验证文件名
            safe_filename = secure_filename(filename)
            if not safe_filename or safe_filename != filename:
                return False, "无效文件名"
            
            filepath = os.path.join(self.upload_dir, safe_filename)
            if not os.path.exists(filepath):
                return False, "文件不存在"
                
            return True, filepath
        except Exception as e:
            self.logger.exception(f"获取文件异常: {str(e)}")
            return False, str(e)